﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BussinessLogicTecnoPez;
using Tecnopez.Globals;
using BussinessLogicTecnoPez.Produccion.Compras;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Validation;

public partial class Modules_Compras_ABMFactores : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.Page.IsPostBack)
        {
            SetMode(PageMode.ListMode);
        }

        InicializarValidadores();
        InicializarGrilla();

        cmdEliminar.OnClientClick = "return confirm('Esta seguro de eliminar el registro?');";

        GenericMasterPage master = (GenericMasterPage)this.Master;
        master.Imagen = "../Styles/Icons/configurar.gif";
        master.Titulo = "Gestión de Factores de Análisis";
        cargarGrilla();
        _lblError.Text = "";
    }

    private void InicializarValidadores()
    {
        PPVDescripcion.SourceTypeName = "BussinessLogicTecnoPez.Produccion.Compras.Factor";
        PPVDescripcion.ControlToValidate = "txtDescripcion";
        PPVDescripcion.PropertyName = "Descripcion";
        PPVDescripcion.DisplayMode = ValidationSummaryDisplayMode.List;
    }

    private void InicializarGrilla()
    {
        grdFactores.setupGrid<Factor>(cargarGrilla, seleccionarFactor, null, true, this.ViewState);
    }

    private void seleccionarFactor(int o)
    {
        int IdFactor = int.Parse(grdFactores.grdDatosAbmView.DataKeys[o].Value.ToString());
        Factor.getManager.ClearFilters();
        Factor.getManager.AddFilter("IDFACTOR", GenericManager<Factor>.filterOperator.Equals, IdFactor);
        Factor objFactor = Factor.getManager.GetOne();
        txtId.Text = objFactor.IdFactor.ToString();
        txtDescripcion.Text = objFactor.Descripcion.Trim();
        if (objFactor.Maximizante)
            rblTipo.SelectedValue = "1";
        else
            rblTipo.SelectedValue = "0";

        SetMode(PageMode.ViewMode);
    }

    private void cargarGrilla()
    {
        Factor.getManager.ClearFilters();
        Factor.getManager.ClearOrders();
        Factor.getManager.AddFilter("Descripcion", GenericManager<Factor>.filterOperator.Like, "%" + txtBuscarDescripcion.Text.Trim() + "%");

        if (!cblTipo.Items[0].Selected && cblTipo.Items[1].Selected || cblTipo.Items[0].Selected && !cblTipo.Items[1].Selected)
        {
            if (cblTipo.Items[0].Selected)
                Factor.getManager.AddFilter("Maximizante", GenericManager<Factor>.filterOperator.Equals, true);
            else
                Factor.getManager.AddFilter("Maximizante", GenericManager<Factor>.filterOperator.Equals, false);
        }

        if (ViewState["orden"] == null)
            Factor.getManager.AddOrder("IdFactor", GenericManager<Factor>.Order.orderDirection.DESC);
        else
            Factor.getManager.AddOrder(ViewState["orden"].ToString(), (GenericManager<Factor>.Order.orderDirection)ViewState["ordenDireccion"]);

        List<Factor> lista = new List<Factor>();
        lista = Factor.getManager.GetFilter();
        grdFactores.grdDatosAbmView.DataSource = lista;
        grdFactores.grdDatosAbmView.DataBind();
    }

    private void SetMode(PageMode mode)
    {
        ViewState["PageMode"] = mode;
        switch (mode)
        {
            case PageMode.ListMode:
                wzrABM.ActiveStepIndex = 0;
                break;
            case PageMode.NewMode:
                wzrABM.ActiveStepIndex = 1;
                txtId.ReadOnly = true;
                txtDescripcion.ReadOnly = false;
                rblTipo.Enabled = true;
                cmdAceptar.Visible = true;
                cmdCancelar.Enabled = true;
                cmdEditar.Enabled = false;
                cmdEliminar.Enabled = false;
                break;
            case PageMode.EditMode:
                wzrABM.ActiveStepIndex = 1;
                txtId.ReadOnly = true;
                txtDescripcion.ReadOnly = false;
                rblTipo.Enabled = true;
                cmdAceptar.Visible = true;
                cmdCancelar.Enabled = true;
                cmdEditar.Enabled = false;
                cmdEliminar.Enabled = false;
                break;
            case PageMode.ViewMode:
                wzrABM.ActiveStepIndex = 1;
                txtId.ReadOnly = true;
                txtDescripcion.ReadOnly = true;
                rblTipo.Enabled = false;
                cmdAceptar.Visible = false;
                cmdCancelar.Enabled = true;
                cmdEditar.Enabled = true;
                cmdEliminar.Enabled = true;
                break;
        }
    }
    protected void cmdEditar_Click(object sender, EventArgs e)
    {
        SetMode(PageMode.EditMode);
    }
    protected void cmdEliminar_Click(object sender, EventArgs e)
    {
        try
        {
            Factor objFactor = new Factor();

            objFactor.IdFactor = int.Parse(txtId.Text.Trim());
            if (Factor.getManager.Delete(objFactor) < 1)
            {
                throw Factor.getManager.GeneratedException;
            }
            SetMode(PageMode.ListMode);
            cargarGrilla();
        }
        catch (Exception exc)
        {
            _lblError.Text = "error: No se pudo realizar la operación";
            Functions.LogError(exc);
            SetMode(PageMode.ListMode);
        }
    }
    protected void cmdAceptar_Click(object sender, EventArgs e)
    {
        try
        {
            Factor objFactor = new Factor();
            objFactor.Descripcion = txtDescripcion.Text.Trim();
            objFactor.Maximizante = int.Parse(rblTipo.SelectedValue) == 1;

            if (validar(objFactor))
            {
                if (getMode() == PageMode.NewMode)
                {
                    if (Factor.getManager.Insert(objFactor) != true)
                    {
                        throw Factor.getManager.GeneratedException;
                    }
                    SetMode(PageMode.ListMode);
                    cargarGrilla();
                }
                else
                {
                    objFactor.IdFactor = int.Parse(txtId.Text.ToUpper().Trim());
                    if (Factor.getManager.Update(objFactor) != true)
                    {
                        throw Factor.getManager.GeneratedException;
                    }
                    SetMode(PageMode.ViewMode);
                }
            }
        }
        catch (Exception exc)
        {
            _lblError.Text = "error: No se pudo realizar la operación";
            Functions.LogError(exc);
            SetMode(PageMode.NewMode);
        }
    }
    private PageMode getMode()
    {
        if (ViewState["PageMode"] == null)
            return PageMode.ModeNotFound;
        return (PageMode)ViewState["PageMode"];
    }

    private bool validar(Factor objeto)
    {
        ValidationResults v = Validation.Validate<Factor>(objeto);
        if (!v.IsValid)
        {
            _lblError.Text = "Error en el formulario: Por favor verifique los campos ingresados.";
        }
        return v.IsValid;
    }
    protected void cmdCancelar_Click(object sender, EventArgs e)
    {
        SetMode(PageMode.ListMode);
    }
    protected void cmdNuevo_Click(object sender, EventArgs e)
    {
        txtId.Text = "";
        txtDescripcion.Text = "";
        rblTipo.SelectedValue = "1";
        SetMode(PageMode.NewMode);
    }
}
